package com.noble.library.permission;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;

import com.noble.library.basic.log.PLogger;
import com.noble.library.basic.sp.PSP;

import java.util.ArrayList;
import java.util.List;

/**
 * 6.0权限工具类
 */
public class MPermissionsUtils {
    private PermissionsResultAction resultAction;

    private static class MPermissionsUtilsLoader {
        private static final MPermissionsUtils INSTANCE = new MPermissionsUtils();
    }

    public static MPermissionsUtils getInstance() {
        return MPermissionsUtilsLoader.INSTANCE;
    }

    /**
     * 申请权限
     */
    public void requestPermissions(Activity activity, int requestCode, String[] permissions, PermissionsResultAction resultAction) {
        this.resultAction = resultAction;
        requestPermissions(activity, requestCode, permissions);
    }


    private void requestPermissions(Activity activity, int requestCode, String[] permissions) {
        List<String> deniedPermissions = findDeniedPermissions(activity, permissions);
        if (deniedPermissions.size() > 0) {
            ActivityCompat.requestPermissions(activity, deniedPermissions.toArray(new String[]{}), requestCode);
        } else {
            if (resultAction != null) resultAction.doExecuteSuccess(requestCode);
        }
    }

    /**
     * 获取没有授权的权限
     */
    private static List<String> findDeniedPermissions(Activity activity, String... permission) {
        List<String> denyPermissions = new ArrayList<>();
        for (String value : permission) {
            if (ActivityCompat.checkSelfPermission(activity, value) != PackageManager.PERMISSION_GRANTED) {
                denyPermissions.add(value);
            }
        }
        return denyPermissions;
    }

    /**
     * 处理结果
     * 在Activity的onRequestPermissionsResult() 方法中调用
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        List<String> deniedPermissions = new ArrayList<>();
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                deniedPermissions.add(permissions[i]);
            }
        }

        if (deniedPermissions.size() > 0) {
            if (resultAction != null) resultAction.doExecuteFail(requestCode);
        } else {
            if (resultAction != null) resultAction.doExecuteSuccess(requestCode);
        }
    }

    /**
     * 回调接口
     */
    public interface PermissionsResultAction {
        void doExecuteSuccess(int requestCode);

        void doExecuteFail(int requestCode);
    }

    // ===================================================================================================

    /**
     * 请求权限
     *
     * @param activity    FragmentActivity实例，用于调起dialog
     * @param permission  当前要请求的权限类型，如：Manifest.permission.READ_CONTACTS
     * @param requestCode 权限请求码，用于回调监听
     * @param runnable    点击确定按钮之后执行的runnable
     */
    public static void getPermission(FragmentActivity activity, String permission, int requestCode, Runnable runnable) {
        if (!isHasPermission(activity, permission)) {
            PSP.getInstance().put(permission, true);
            if (Build.VERSION.SDK_INT >= 23 && getTargetVersion(activity) >= 23) {
                ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
            } else {
                if (runnable != null) runnable.run();
            }
        } else {
            PLogger.d("---PermissionUtils--->已有权限，或不需要展示权限弹框");
        }
    }

    /**
     * @return 获取当前app的targetSdkVersion
     */
    private static int getTargetVersion(Context context) {
        int targetSdkVersion = 0;
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return targetSdkVersion;
    }

    private static boolean isHasPermission(Context context, String permission) {
        // For Android < Android M, self permissions are always granted.
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            if (getTargetVersion(context) >= 23) {//代码兼容
                result = ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
                PLogger.d("---PermissionUtils--->Build.VERSION.SDK_INT >= 23，targetSdkVersion >= 23");
            } else {//targetVersion<23的时候权限获取依旧遵循原有的方式，默认无权限
                PLogger.d("---PermissionUtils--->Build.VERSION.SDK_INT >= 23，targetSdkVersion < 23");
                result = PSP.getInstance().getBoolean(permission, false);
            }
        } else {
            PLogger.d("---PermissionUtils--->Build.VERSION.SDK_INT < 23");
            result = PSP.getInstance().getBoolean(permission, false);
        }
        PLogger.d("---PermissionUtils--->" + permission + "：" + result);
        return result;
    }
}
